package com.lottoad.android.activity;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Process;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.lottoad.android.R;
import com.lottoad.android.activity.info.LottoAdInfoAdressActivity;
import com.lottoad.android.common.BaseActivity;
import com.lottoad.android.cronos.http.CNHttpManager;
import com.lottoad.android.cronos.http.CNLottoAdApiSet;
import com.lottoad.android.cronos.http.CNLottoAdApiSetEx;
import com.lottoad.android.util.ApplicationUtils;
import com.lottoad.android.util.CNCronosLog;
import com.lottoad.android.util.LottoAdConstants;

/**
 * 인트로 Activity
 * @author Administrator
 *
 */
public class LottoAdIntroActivity extends BaseActivity {
	
	private final int ACTIVITY_REQUEST_AGREE = 1;

	private Context mContext;
	private Handler mHandler;
	
	private TextView mVerTextView;

	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_intro;
	}

	@Override
	protected void onInit() {
		this.mContext = this;
		/*####### Ben ########*/
		// 푸시토큰 테스트
		String token = ApplicationUtils.getStrPreferences(this, LottoAdConstants.PREFER_REGISTRATION_ID);
		if(token == null || token.equals("")) {
			onPushSetting();
		}
		
		mVerTextView = (TextView) findViewById(R.id.textView_version);
		mVerTextView.setText("Ver " + ApplicationUtils.getAppVersionName(mContext));
		
		LottoAdConstants.PHONE_NUMBER = ApplicationUtils.getPhoneNumber(mContext);			// 전화번호 가져오기
		
		if(!CNLottoAdApiSet.isLive()){
			Toast.makeText(mContext, "개발 서버 입니다.", Toast.LENGTH_SHORT).show();
		}

		mHandler = new Handler();

		if(LottoAdConstants.PHONE_NUMBER != null && LottoAdConstants.PHONE_NUMBER.length() > 0){
			if(!CNHttpManager.getNetworkStatus(mContext))		// 네트워크 상태 체크
			{
				ApplicationUtils.showOkDialog(mContext,0, getString(R.string.popup_alert),ApplicationUtils.getErrorMessage(mContext, 4), onOkClickListener);
				return;
			}
			else
			{
				onRequestData();
			}
		}
	}

	private class GoMainHandler implements Runnable {
		
		private boolean mIsMember;
		
		public GoMainHandler(boolean isMember){
			this.mIsMember = isMember;
		}
		
		@Override
		public void run() {
			Intent intent = null;
			/*####### Ben ########*/
			// 회원가입 페이지 바로 넘김 테스트
			if (mIsMember) {
				ApplicationUtils.setBoolPreferences(mContext,
						LottoAdConstants.PREPERENCE_IS_REGISTER, true);
				intent = new Intent(mContext, LottoAdMainActivity.class);
				startActivity(intent);
				finish();
			} else {
				intent = new Intent(mContext, LottoAdAgreeActivity.class);
				startActivityForResult(intent, ACTIVITY_REQUEST_AGREE);
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == ACTIVITY_REQUEST_AGREE) {
			if (resultCode == RESULT_OK) {
				Intent intent = new Intent(mContext,
						LottoAdInfoAdressActivity.class);
				startActivity(intent);
				finish();
			} else if (resultCode == RESULT_CANCELED) {
				finish();
			}
		}
	}
	
	private DialogInterface.OnClickListener onOkClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
			finish();
			Process.killProcess(0);
		}
	};

	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");

		String url = null;

		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.checkMemberUrl(mContext,
				LottoAdConstants.PHONE_NUMBER);
		CNCronosLog.d("onGetAsyncRequestUrl", "url : " + url);
		return url;
	}

	@Override
	public void onAsyncCancelRequest() {
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage) {
		super.hideLoadingDialog();
		
		CNCronosLog.d("onAsyncDataError()");
		
		NodeList rcodeNode = xmlObject.getElementsByTagName("rcode");
		String rcode = rcodeNode.item(0).getFirstChild().getNodeValue();
		
		Log.w("BenTag", "onAsyncDataError!! rcode : " + rcode);
		if(!"RET0003".equals(rcode)){
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), errorMessage);
		} else {
			mHandler.postDelayed(new GoMainHandler(false), 0);
			onPushSetting();
		}
	}

	@Override
	public void onAsyncPreRequest() {
		super.showLoadingDialog(mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject) {
		super.hideLoadingDialog();
		
		try {
			mHandler.postDelayed(new GoMainHandler(true), 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncRequestError()");
		
		 ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), 
				 ApplicationUtils.getErrorMessage(mContext, errorNumber),onOkClickListener);
		 return;
	}
	
	/**
	 * PushSetting (Registration ID 등록)
	 */
	private void onPushSetting()
	{
		if(ApplicationUtils.getStrPreferences(mContext, LottoAdConstants.PREFER_REGISTRATION_ID) == null || 
			ApplicationUtils.getStrPreferences(mContext, LottoAdConstants.PREFER_REGISTRATION_ID).equals("")){

				Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
			    registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
			    registrationIntent.putExtra("sender", "51503619014");
			    startService(registrationIntent);
			}
	}
}
